<template>
  <div class="h-full">
    <a-button @click="handleEdit"> {{ label }}</a-button>
  </div>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="register"
    showFooter
    title="方法定义"
    width="60%"
    @height-change="handleHeightChange"
    @ok="handleSubmit"
  >
    <!--  <FormTitle text="基础设置" class="ml-4" /> -->
    <CodeMirrorEditor
      :style="{
        height,
      }"
      v-model:value="getValue"
      @change="handleChange"
      :readonly="readonly"
      :mode="mode"
      ref="codeMirrorEditor"
    />
  </BasicModal>
</template>
<script lang="ts" setup name="ButtonCodeEditor">
  import { ref, computed, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import CodeMirrorEditor from './codemirror/CodeMirror.vue';
  import { isString } from '/@/utils/is';
  import { MODE } from './typing';

  const props = defineProps({
    value: { type: [Object, String] as PropType<Record<string, any> | string> },
    label: {
      type: String,
      default: '编辑',
    },
    mode: {
      type: String as PropType<MODE>,
      default: MODE.JS,
      validator(value: any) {
        // 这个值必须匹配下列字符串中的一个
        return Object.values(MODE).includes(value);
      },
    },
    readonly: { type: Boolean },
    autoFormat: { type: Boolean, default: true },
  });

  const emit = defineEmits(['change', 'update:value', 'format-error', 'register']);
  const height = ref('764px');
  const getValue = computed(() => {
    const { value, mode, autoFormat } = props;
    if (!autoFormat || mode !== MODE.JSON) {
      return value as string;
    }
    let result = value;
    if (isString(value)) {
      try {
        result = JSON.parse(value);
      } catch (e) {
        emit('format-error', value);
        return value as string;
      }
    }
    return JSON.stringify(result, null, 2);
  });

  const currentValue = ref<any>('');
  const [register, { setModalProps, closeModal }] = useModalInner();
  const codeMirrorEditor = ref();
  const handleEdit = () => {
    setModalProps({ open: true, defaultFullscreen: true });
  };

  watch(
    () => props.value,
    (v) => {
      currentValue.value = v;
    },
  );
  function handleSubmit() {
    emit('update:value', currentValue.value);
    emit('change', currentValue.value);
    closeModal();
  }

  function handleChange(v) {
    currentValue.value = v;
  }
  function handleHeightChange(v) {
    if (parseFloat(height.value) === v) return;

    height.value = v + 'px';
    setTimeout(() => {
      codeMirrorEditor.value.refresh();
    });
  }
</script>
<style lang="less" scoped></style>
